import requests
import json
import random
import time
from urllib.parse import urlencode

def get_weibo_user_info(user_id, retry_count=3):
    """
    获取微博用户信息的函数
    
    Args:
        user_id: 微博用户ID
        retry_count: 重试次数，默认为3次
    
    Returns:
        dict: 用户信息字典，如果失败返回None
    """
    # 构造API URL
    container_id = f"107603{user_id}"
    url = f"https://m.weibo.cn/api/container/getIndex?type=uid&value={user_id}&containerid={container_id}"
    
    # 生成随机令牌
    xsrf_token = ''.join(random.choices('0123456789abcdef', k=6))
    short_token = ''.join(random.choices('0123456789abcdef', k=10)) if random.random() > 0.5 else None
    
    # 构造M_WEIBOCN_PARAMS参数
    m_params = {
        'luicode': '10000011',
        'lfid': container_id,
        'fid': container_id,
        'uicode': '10000011'
    }
    m_params_encoded = urlencode(m_params)
    
    # 设置Cookie
    cookies = {
        '_T_WM': '19821358581',
        'M_WEIBOCN_PARAMS': m_params_encoded,
        'MLOGIN': '0',
        'WEIBOCN_FROM': '1110006030',
        'XSRF-TOKEN': xsrf_token
    }
    
    if short_token:
        cookies['mweibo_short_token'] = short_token
    
    # 设置请求头
    headers = {
        'User-Agent': 'Mozilla/5.0 (iPhone; CPU iPhone OS 13_2_3 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/13.0.3 Mobile/15E148 Safari/604.1',
        'Accept': 'application/json, text/plain, */*',
        'Accept-Language': 'zh-CN,zh;q=0.9,en;q=0.8',
        'Referer': f'https://m.weibo.cn/u/{user_id}',
        'X-Requested-With': 'XMLHttpRequest'
    }
    
    # 重试机制
    for attempt in range(retry_count):
        try:
            response = requests.get(url, headers=headers, cookies=cookies, timeout=10)
            
            if response.status_code != 200:
                print(f"请求失败，状态码: {response.status_code}，尝试 {attempt+1}/{retry_count}")
                time.sleep(2)
                continue
                
            # 尝试解析JSON
            try:
                data = response.json()
                if data.get('ok') == 1:
                    print(data['data'])
                    return data['data']
                else:
                    print(f"API响应失败: {data.get('msg', '未知错误')}")
            except json.JSONDecodeError:
                print(f"JSON解析错误，尝试 {attempt+1}/{retry_count}")
                print(f"响应内容: {response.text[:200]}...")
                
            time.sleep(2)
            
        except requests.exceptions.RequestException as e:
            print(f"请求异常: {e}，尝试 {attempt+1}/{retry_count}")
            time.sleep(2)
    
    return None
# 获取微博随机cookie
def get_weibo_rand_cookie(user_id, count=10, retry_count=3):
    print("用户id用户id用户id");
    print(f"107603{user_id}")
    print("用户id用户id用户id");
    """
    获取用户微博内容的函数
    
    Args:
        user_id: 微博用户ID
        count: 获取的微博数量，默认为10
        retry_count: 重试次数，默认为3次
    
    Returns:
        list: 微博列表，如果失败返回空列表
    """
    # 构造API URL
    container_id = f"107603{user_id}"
    url = f"https://m.weibo.cn/api/container/getIndex?type=uid&value={user_id}&containerid={container_id}&count={count}"
    
    # 生成随机令牌
    xsrf_token = ''.join(random.choices('0123456789abcdef', k=6))
    short_token = ''.join(random.choices('0123456789abcdef', k=10)) if random.random() > 0.5 else None

    
    # 构造M_WEIBOCN_PARAMS参数
    m_params = {
        'luicode': '10000011',
        'lfid': container_id,
        'fid': container_id,
        'uicode': '10000011'
    }
    m_params_encoded = urlencode(m_params)
    
    # 设置Cookie
    cookies = {
        '_T_WM': '19821358581',
        'M_WEIBOCN_PARAMS': m_params_encoded,
        'MLOGIN': '0',
        'WEIBOCN_FROM': '1110006030',
        'XSRF-TOKEN': xsrf_token
    }
    if short_token:
        cookies['mweibo_short_token'] = short_token
    return cookies

def get_weibo_user_tweets(user_id, count=10, retry_count=3):
    """
    获取用户微博内容的函数
    
    Args:
        user_id: 微博用户ID
        count: 获取的微博数量，默认为10
        retry_count: 重试次数，默认为3次
    
    Returns:
        list: 微博列表，如果失败返回空列表
    """
    # 构造API URL
    container_id = f"107603{user_id}"
    url = f"https://m.weibo.cn/api/container/getIndex?type=uid&value={user_id}&containerid={container_id}&count={count}"
    
    # 生成随机令牌
    xsrf_token = ''.join(random.choices('0123456789abcdef', k=6))
    
    # 构造M_WEIBOCN_PARAMS参数
    m_params = {
        'luicode': '10000011',
        'lfid': container_id,
        'fid': container_id,
        'uicode': '10000011'
    }
    m_params_encoded = urlencode(m_params)
    
    # 设置Cookie
    cookies = {
        '_T_WM': '19821358581',
        'M_WEIBOCN_PARAMS': m_params_encoded,
        'MLOGIN': '0',
        'WEIBOCN_FROM': '1110006030',
        'XSRF-TOKEN': xsrf_token
    }
    
    # 设置请求头
    headers = {
        'User-Agent': 'Mozilla/5.0 (iPhone; CPU iPhone OS 13_2_3 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/13.0.3 Mobile/15E148 Safari/604.1',
        'Accept': 'application/json, text/plain, */*',
        'Accept-Language': 'zh-CN,zh;q=0.9,en;q=0.8',
        'Referer': f'https://m.weibo.cn/u/{user_id}',
        'X-Requested-With': 'XMLHttpRequest'
    }
    
    # 重试机制
    for attempt in range(retry_count):
        try:
            response = requests.get(url, headers=headers, cookies=cookies, timeout=10)
            
            if response.status_code != 200:
                print(f"请求失败，状态码: {response.status_code}，尝试 {attempt+1}/{retry_count}")
                time.sleep(2)
                continue
                
            # 尝试解析JSON
            try:
                data = response.json()
                if data.get('ok') == 1:
                    # 提取微博卡片
                    tweets = []
                    for card in data['data'].get('cards', []):
                        if card.get('card_type') == 9:  # 微博卡片类型
                            tweets.append(card.get('mblog', {}))
                    return tweets
                else:
                    print(f"API响应失败: {data.get('msg', '未知错误')}")
            except json.JSONDecodeError:
                print(f"JSON解析错误，尝试 {attempt+1}/{retry_count}")
                print(f"响应内容: {response.text[:200]}...")
                
            time.sleep(2)
            
        except requests.exceptions.RequestException as e:
            print(f"请求异常: {e}，尝试 {attempt+1}/{retry_count}")
            time.sleep(2)
    
    return []

# 使用示例
if __name__ == "__main__":
    # 获取用户信息
    user_id = "1987241375"
    user_info = get_weibo_user_info(user_id)
    
    if user_info:
        print(f"用户 {user_id} 的信息:")
        print(f"用户名: {user_info.get('screen_name', '未知')}")
        print(f"粉丝数: {user_info.get('followers_count', 0)}")
        print(f"微博数: {user_info.get('statuses_count', 0)}")
        print(f"简介: {user_info.get('description', '无')}")
    else:
        print(f"获取用户 {user_id} 信息失败")
    
    # 获取用户微博
    tweets = get_weibo_user_tweets(user_id, 5)
    if tweets:
        print(f"\n用户 {user_id} 的最新微博:")
        for i, tweet in enumerate(tweets, 1):
            print(f"{i}. {tweet.get('created_at', '未知时间')}: {tweet.get('text', '无内容')[:50]}...")
    else:
        print(f"获取用户 {user_id} 微博失败")
